<template>
    <div>


        <!-- 创建文档按钮 -->
        <el-button type="primary" @click="showCreateDialog" style="margin-top: 20px;">创建文档</el-button>


        <!-- 文档列表 -->
        <el-table :data="documents" style="width: 100%">
            <el-table-column prop="id" label="ID"  />
            <el-table-column prop="content" label="内容"  />
            <el-table-column prop="createdAt" label="创建时间"  :formatter="formatDate" />
            <el-table-column prop="updatedAt" label="更新时间"  :formatter="formatDate" />
            <el-table-column prop="employeeNumber" label="添加人工号" width="150" />

            <!-- 操作列 -->
            <el-table-column label="操作" width="200">
                <template v-slot="scope">
                    <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" @click="deleteDocument(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 编辑文档对话框 -->
        <el-dialog title="编辑文档" v-model="editDialogVisible">
            <el-form :model="selectedDocument" label-width="120px">
                <el-form-item label="内容">
                    <el-input v-model="selectedDocument.content" type="textarea" :rows="5"></el-input>
                </el-form-item>
                <el-form-item label="添加人工号">
                    <el-input v-model="selectedDocument.employeeNumber" disabled></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updateDocument">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 创建文档对话框 -->
        <el-dialog title="创建文档" v-model="createDialogVisible">
            <el-form :model="newDocument" label-width="120px">
                <el-form-item label="内容">
                    <el-input v-model="newDocument.content" type="textarea" :rows="5"></el-input>
                </el-form-item>
                <el-form-item label="添加人工号">
                    <el-input v-model="newDocument.employeeNumber" disabled></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="createDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="createDocument">确 定</el-button>
                </span>
            </template>
        </el-dialog>


    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import service from "@/utils/request";
import { ElMessage, ElMessageBox } from 'element-plus';

// 文档数据
const documents = ref([]);

// 编辑对话框显示状态
const editDialogVisible = ref(false);

// 创建对话框显示状态
const createDialogVisible = ref(false);

// 当前选中的文档
const selectedDocument = ref({

    employeeNumber: localStorage.getItem('employeeNumber') || '', // 从 localStorage 获取工号
});



// 新文档
const newDocument = ref({
    content: '',
    employeeNumber: localStorage.getItem('employeeNumber') || '', // 从 localStorage 获取工号
    // console.log(newDocument.value.employeeNumber)
});

/**
 * 格式化日期函数
 * @param {Object} row - 表格行数据
 * @param {Object} column - 表格列数据
 * @param {string} cellValue - 单元格值
 * @returns {string} 格式化后的日期字符串
 */
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const date = new Date(cellValue);
    if (isNaN(date.getTime())) return 'Invalid Date';
    return date.toLocaleString('zh-CN');
};

/**
 * 获取文档数据
 */
const fetchDocuments = async () => {
    try {
        const response = await service.get('/admin/documents');
        documents.value = response.data;
    } catch (error) {
        console.error('获取文档数据失败', error);
        ElMessage.error('获取文档数据失败');
    }
};

/**
 * 显示编辑对话框
 * @param {Object} document - 当前选中的文档
 */
const showEditDialog = (document) => {
    selectedDocument.value = { ...document };
    editDialogVisible.value = true;
};

/**
 * 更新文档信息
 */
const updateDocument = async () => {
    try {
        await service.put(`/admin/documents/${selectedDocument.value.id}`, selectedDocument.value);
        await fetchDocuments();
        editDialogVisible.value = false;
        ElMessage.success('文档更新成功');
    } catch (error) {
        console.error('更新文档失败', error);
        ElMessage.error('文档更新失败');
    }
};

/**
 * 删除文档
 * @param {number} id - 文档 ID
 */
const deleteDocument = async (id) => {
    try {
        await ElMessageBox.confirm('确定删除该文档吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });
        await service.delete(`/admin/documents/${id}`);
        await fetchDocuments();
        ElMessage.success('文档删除成功');
    } catch (error) {
        console.error('删除文档失败', error);
        ElMessage.error('文档删除失败');
    }
};

/**
 * 显示创建文档对话框
 */
const showCreateDialog = () => {
    newDocument.value = {
        content: '',
        employeeNumber: localStorage.getItem('employeeNumber') || '' // 重新从 localStorage 获取工号
    };
    createDialogVisible.value = true;
};

/**
 * 创建文档
 */
const createDocument = async () => {
    try {
        await service.post('/admin/documents', newDocument.value);
        await fetchDocuments();
        createDialogVisible.value = false;
        ElMessage.success('文档创建成功');
    } catch (error) {
        console.error('创建文档失败', error);
        ElMessage.error('文档创建失败');
    }
};

// 组件挂载时获取文档数据
onMounted(() => {
    fetchDocuments();
});
</script>